import Vue from "vue";
import Router from 'vue-router'

import store from "@/store";

import { message } from 'ant-design-vue'

Vue.use(Router)


export const currencyRoutes = [
  {
    path: "/login",
    name: "Login",
    title:"登录页",
    component: () =>
      import("@/views/Login"),
  },


];

export const asyncRoutes = [

  {
    path: "",
    name: "Layout",
    component: () => import("@/layout/index.vue"),
    redirect: '/index',
    title: '首页',
    children: [

      {
        path: "/index",
        name: "Index",
        title:"首页",
        component: () =>
          import("@/views/Index"),
      },
    ],
  },

];














const creatRouter = () => {
  return new Router({
    routes: currencyRoutes,
    scrollBehavior() {
      return { x: 0, y: 0 }
    }
  })
}

const router = creatRouter()

// 解决addRoute不能删除动态路由问题
export function resetRouter() {
  const reset = creatRouter()
  router.matcher = reset.matcher
}

// const router = new VueRouter({
//   mode: "hash",
//   base: process.env.BASE_URL,
//   routes,
// });
// // 导航守卫
router.beforeEach(async (to, from, next) => {
  // document.title = getTitle(to.meta.title)
  if (to.path === '/login') {
    next()
  } else {
    console.log(657);
    if (store.getters.token) {
      const hasRoles = store.state.permission.routes.length > 0

      if (hasRoles) {

        next()
      } else {

        try {
          const {roles } =  await store.dispatch('user/_getInfo')
          console.log(store.dispatch('user/_getInfo'),"----------------");
          const addRoutes = await store.dispatch(
            'permission/getAsyncRoutes',
            roles
          )
          console.log(roles,addRoutes,"9999999999999");
          router.addRoutes(addRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          message.error(error)
        }
      }
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  }
})


export default router;
